package village.rainbow.slipin.util;

import village.rainbow.slipin.DataProvider;
import village.rainbow.slipin.R;
import village.rainbow.slipin.ui.ViewSlipActivity;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;

public class ShortcutUtil {
	
	private Context mContext;
	private DataProvider mContentProvider;
	
	public ShortcutUtil (Context context, DataProvider provider){
		mContext = context;
		mContentProvider = provider;
	}
	
	
	public void shorcutScene(Bitmap bitmap, String sceneId, String sceneTxt) throws Exception {
		uninstallShortcut(sceneId, sceneTxt);
		installShortcut(bitmap, sceneId, sceneTxt);
	}

	private void uninstallShortcut(String sceneId, String sceneTxt) {
		ContentValues values = new ContentValues();
		values.put("SCENE_ID", sceneId);
		
		Uri uri = mContentProvider.insert(DataProvider.CONTENT_URI, values);
		
		Intent shortcutIntent = new Intent(mContext, ViewSlipActivity.class);
		shortcutIntent.setData(uri);
		shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		shortcutIntent.setAction(Intent.ACTION_MAIN);
	     
	    Intent addIntent = new Intent();
	    addIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
	    addIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, sceneTxt);
	    addIntent.setAction("com.android.launcher.action.UNINSTALL_SHORTCUT");
	    mContext.sendBroadcast(addIntent);
	}
	
	private void installShortcut(Bitmap bitmap, String sceneId, String sceneTxt) {
		ContentValues values = new ContentValues();
		values.put("SCENE_ID", sceneId);
		
		Uri uri = mContentProvider.insert(DataProvider.CONTENT_URI, values);
		
		Intent shortcutIntent = new Intent(mContext, ViewSlipActivity.class);
		shortcutIntent.setData(uri);
		shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		shortcutIntent.setAction(Intent.ACTION_MAIN);

		Intent addIntent = new Intent();
		addIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
		addIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, sceneTxt);
		
		if(bitmap == null){
			addIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, Intent.ShortcutIconResource.fromContext(mContext, R.drawable.ic_launcher));
		}else{
			Bitmap iconBitmap = Bitmap.createScaledBitmap(bitmap, 128, 128, true);
			addIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON, iconBitmap);
		}
		addIntent.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
		mContext.sendBroadcast(addIntent);
	}

	
}
